package com.ebelter.btlibrary.btble.impl.scale;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;

import com.ebelter.btlibrary.btble.ble.BleManager;
import com.ebelter.btlibrary.btble.ble.bluetooth.callback.ConnectCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.BlueToothServer;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.OnDeviceBindFoundListener;
import com.ebelter.btlibrary.btble.ble.model.BleConfigure;
import com.ebelter.btlibrary.btble.ble.model.BleDevice;
import com.ebelter.btlibrary.btble.common.Fields;
import com.ebelter.btlibrary.btble.impl.scale.callback.IMeasureResultCallback;
import com.ebelter.btlibrary.btble.impl.scale.callback.WeightUnitChangedCallback;
import com.ebelter.btlibrary.btble.impl.scale.model.FileType;
import com.ebelter.btlibrary.btble.impl.scale.model.ScaleUser;
import com.ebelter.btlibrary.btble.impl.scale.upgrade.FirmwareUpgradeCallback;
import com.ebelter.btlibrary.btble.impl.scale.upgrade.FirmwareUpgrader;
import com.ebelter.btlibrary.util.SpUtil;


/**
 * 体脂秤蓝牙管理者
 * Created by Sergio Pan on 2017/12/8.
 */

public class ScaleBle extends BleManager {

    private static ScaleMessageAnalyser analyser;
    private static ScaleCommondEditor editor;
    private static ScaleBle instance;

    private ScaleBle() {

    }

    //同步时钟
    public void syncSystemClock(){
        if (editor!=null){
            editor.syncSystemClock();
        }
    }

    public static synchronized ScaleBle getInstance() {
        if (instance == null) {
            instance = new ScaleBle();
        }
        return instance;
    }

    /**
     * 1. 初始化蓝牙服务
     */
    @Override
    protected void initBleService(Activity aty) {
        if (aty == null) {
            return;
        }
        //打开蓝牙
        open(aty);
        //创建实例
        analyser = ScaleMessageAnalyser.getInstance();
        mBlueToothServer = BlueToothServer.getInstance(aty.getApplicationContext());
        mBlueToothServer.registerScanResultCallback(scanResultCallback);
        mBlueToothServer.registerConnectCallback(mConnectCallback);
        mBlueToothServer.registerBleMessageAnalyser(analyser);
        editor = ScaleCommondEditor.getInstance();
        editor.registerBleMessageWriter(mBlueToothServer);
        analyser.registerInternalChannel(editor);

        //已绑定设备开始扫描
//        if (instance.isDeviceBound()) {
//            instance.startScan();
//        }

        //注册固件升级服务
        FirmwareUpgrader mFirmwareUpgrader = FirmwareUpgrader.getInstance();
        analyser.registerFirmwareUpgradeCallback(mFirmwareUpgrader.getFirmwareUpgradeCallback());
        mFirmwareUpgrader.init(aty.getApplicationContext(), editor);
        //注册息屏监听广播
        instance.registSreenStatusReceiver();
    }


    @Override
    protected void setBleParams() {
        //设置数据头
        BleConfigure configure = BleDevice.getInstance().getConfigure();
        analyser.setDataHeaderReceive(configure.getDataHaderReceive());
        editor.setDataHeaderSend(configure.getDataHeaderSend());
    }


    @Override
    public void registerConnectCallback(ConnectCallback callback) {
        super.registerConnectCallback(callback);
        analyser.registerConnectCallback(callback);
    }

    @Override
    public void disConnectDevice() {
        editor.stopConnHeartbeat();
        super.disConnectDevice();
    }


    @Override
    public void unbindDevice() {
        super.unbindDevice();
        SpUtil.writeString(Fields.DEVICE_MAC,null);
        SpUtil.writeString(Fields.DEVICE_Name,null);
    }

    public void registerMeasureResultCallback(IMeasureResultCallback callback) {
        analyser.registerMeasureResultCallback(callback);
    }

    public void registerWeightUnitChangedCallback(WeightUnitChangedCallback callback) {
        analyser.registerWeightUnitChangedCallback(callback);
    }

    public void registerFirmwareUpgradeCallback(FirmwareUpgradeCallback callback) {
        FirmwareUpgrader.getInstance().registerFirmwareUpgradeCallback(callback);
    }

    /**
     * 设置用户信息
     */
    public void setUserInfo(ScaleUser user) {
        editor.setUserInfo(user);
    }


    /**
     * 请求历史数据
     */
    public void requestHistoryRecords(String uid) {
        editor.requestHistoryRecords(uid);
    }


    //发送获取到历史数据的ACK
    public void sendGetHistoryACK() {
        editor.sendGetHistoryACK();
    }

    //发送获取到测量数据的ACK
    public void sendMesureACK() {
        editor.sendMesureACK();
    }

    /**
     * 8. 清除用户信息
     */
    public void requestDelAllUser() {
        editor.requestDelAllUser();
    }

    /**
     * 11. 请求秤固件升级
     */
    public void requestScaleFirmwareUpgrade() {
        FirmwareUpgrader.requestFirmwareUpgrade(FileType.SCALE_FIRMWARE);
    }

    /**
     * 12. 请求蓝牙固件升级
     */
    public void requestBleFirmwareUpgrade() {
        FirmwareUpgrader.requestFirmwareUpgrade(FileType.BLE_FIRMWARE);
    }


    private static ConnectCallback mConnectCallback = new ConnectCallback() {
        @Override
        public void onConnected(BluetoothDevice device) {
            //TODO 设置蓝牙设备参数
            mBlueToothServer.stopScanDevice();
            if (customConnectCallback != null) {
                customConnectCallback.onConnected(device);
            }

            //绑定设备
//            SharePrefrenceHelper spf = new SharePrefrenceHelper(mActivity.getApplicationContext());
//            spf.open(FileNames.STRING_FILE);
//            spf.putString(Fields.DEVICE_MAC, device.getAddress());
           SpUtil.writeString(Fields.DEVICE_MAC,device.getAddress());
           SpUtil.writeString(Fields.DEVICE_Name,device.getName());

            OnDeviceBindFoundListener.mac = device.getAddress();

            //请求秤版本信息
            editor.requestScaleVersion();
            instance.mConnectStatus = ConnectStatus.CONNECTED;
        }

        @Override
        public void onScaleWake() {
            if (customConnectCallback != null) {
                customConnectCallback.onScaleWake();
            }
        }

        @Override
        public void onScaleSleep() {
            if (customConnectCallback != null) {
                customConnectCallback.onScaleSleep();
            }
        }

        @Override
        public void onDisConnected() {
            if (customConnectCallback != null) {
                customConnectCallback.onDisConnected();
            }
            editor.stopConnHeartbeat();
            instance.mConnectStatus = ConnectStatus.DISCONNECTED;
        }
    };


    /**
     * 停止扫描
     */
    public void stopScan() {
        if (mBlueToothServer!=null){
            mBlueToothServer.stopScanDevice();
        }
    }
}
